<?php

namespace Logic;

/**
 * taobao api封装
 */
class TaoApi {

    /**
     * 查询商品.
     */
    public static function getProducts($cid = 0, $q = "", $minCommissionRate = 100, $hasCoupon = false, $page = 1, $pageSize = 100, $sort = "total_sales_des", $goodRae = false, $needPrepay = false, $payRate = false, $rfdRate = false, $try_times = 0) {
        
        if ($try_times > \Config\System::$site['trytimes']) {
            return [];
        }
        
        $tc = \App::createTopClient();
        $adzoneId = explode('_', \Config\System::$site['mmxxid'])[3];
        $req = new \TbkDgMaterialOptionalRequest();
        $req->setPageSize($pageSize);
        $req->setPageNo($page);
        //$req->setStartTkRate($minCommissionRate); // 淘客佣金比率下限
        //$req->setEndTkRate("8000"); // 淘客佣金比率上限
        //$req->setStartPrice("5"); // 最低折扣价
        //$req->setEndPrice("9999"); // 最高折扣价
        $req->setSort($sort); // 排序方式

        if ($cid) {
            // 设置分类
            $req->setCat($cid);
        }

        if ($q) {
            // 设置关键词
            $req->setQ($q);
        }

        if ($hasCoupon) {
            $req->setHasCoupon("true"); // 是否有券
        }

        $req->setAdzoneId($adzoneId);

        if ($needPrepay) {
            $req->setNeedPrepay("true"); // 加入消费者保障
        }

        if ($payRate) {
            $req->setIncludePayRate30("true"); // 成交转化高于行业
        }

        if ($goodRae) {
            $req->setIncludeGoodRate("true"); // 好评率高于行业
        }

        if ($rfdRate) {
            $req->setIncludeRfdRate("true"); // 退款率是否低于行业均值
        }

        $resp = $tc->execute($req);
        if (isset($resp->code)) {
            $try_times++;
            return self::getProducts($cid, $q, $minCommissionRate, $hasCoupon, $page, $pageSize, $sort, $goodRae, $needPrepay, $payRate, $rfdRate, $try_times);
        }
        
        return $resp;
    }

    /**
     * 查询商品详情
     */
    public static function getDetails($productIds = [], $try_times = 0) {

        if ($try_times > \Config\System::$site['trytimes']) {
            return [];
        }

        $tc = \App::createTopClient();
        $req = new \TbkItemInfoGetRequest();
        $req->setNumIids(implode(',', $productIds));
        $resp = $tc->execute($req);

        if (isset($resp->code)) {
            $try_times++;
            return self::getDetails($productIds, $try_times);
        }

        if (isset($resp->results) && empty($resp->results->n_tbk_item)) {
            // 返回空消息
            return [];
        }

        return static::formatProduct($resp->results->n_tbk_item);
    }

    /**
     * 查询物料
     */
    public static function getMaterialData($materialId = 0, $page = 1, $pageSize = 20, $try_times = 0) {

        if ($try_times > \Config\System::$site['trytimes']) {
            return [];
        }

        $tc = \App::createTopClient();
        $adzoneId = explode('_', \Config\System::$site['mmxxid'])[3];

        $req = new \TbkDgOptimusMaterialRequest();
        $req->setAdzoneId($adzoneId);
        $req->setPageNo($page);
        $req->setPageSize($pageSize);
        $req->setMaterialId($materialId);
        $resp = $tc->execute($req);

        if (isset($resp->code)) {
            $try_times++;
            return self::getMaterialData($materialId, $page, $pageSize, $try_times);
        }

        if (isset($resp->result_list) && isset($resp->result_list->map_data) && $resp->result_list->map_data) {
            return $resp->result_list->map_data;
        }

        return [];
    }

    /**
     * 解析淘口令
     * @param string $taocode_string 包含淘口令的字符串
     */
    public static function parseTaocode($taocode_string = '', $try_times = 0) {
        if ($try_times > \Config\System::$site['trytimes']) {
            return [];
        }

        $tc = \App::createTopClient();
        $req = new \WirelessShareTpwdQueryRequest();
        $req->setPasswordContent($taocode_string);
        $resp = $tc->execute($req);

        if (isset($resp->code)) {
            $try_times++;
            return self::parseTaocode($taocode_string, $try_times);
        }

        return $resp;
    }

    /**
     * 生成淘宝客淘口令
     */
    public static function createTbkTaocode($text = '', $url = '', $logo = '', $try_times = 0) {

        if ($try_times > \Config\System::$site['trytimes']) {
           return '';
        }

        $tc = \App::createTopClient();
        $req = new \TbkTpwdCreateRequest();
        $req->setText($text);
        $req->setUrl($url);
        $req->setLogo($logo);
        $req->setExt("{}");

        $resp = $tc->execute($req);

        if (isset($resp->code)) {
            $try_times++;
            return self::createTbkTaocode($text, $url, $logo, $try_times);
        }

        $taocode = '';
        if (isset($resp->data) && isset($resp->data->model)) {
            $taocode = $resp->data->model;
        }

        return $taocode;
    }

    /**
     * 商品数据格式化
     */
    private static function formatProduct($result) {
        $return = [];
        foreach ($result as $r) {
            $return[$r->num_iid] = [
                'product_id' => $r->num_iid,
                'pict_url' => $r->pict_url,
                'title' => $r->title,
                'volume' => $r->volume,
                'zk_final_price' => $r->zk_final_price,
                'small_images' => isset($r->small_images->string) ? $r->small_images->string : [],
            ];
        }

        return $return;
    }

}
